package com.demo.lottery;

import com.demo.common.model.Staff;
import com.jfinal.core.Controller;
import org.apache.log4j.Logger;
import org.eclipse.jetty.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author caizhongjie
 * @date 2018/1/3 下午1:28
 */
public class LotteryController extends Controller{
    private LotteryService lotteryService = new LotteryService();
    private static final Logger logger = Logger.getLogger(LotteryController.class);

    /**
     * 员工抽奖
     */
    public void register(){
        String staffName = getPara("staff_name");
        String phone = getPara("phone");
        //判断用户是否存在
        if (lotteryService.isExistStaff(staffName,phone)){
            redirect("/error");
        }
        else {
            StringBuilder sb = new StringBuilder();
            Random random = new Random();
            int s = random.nextInt(999);
            sb.append("888").append(String.format("%03d",s));
            String luckyNumber = sb.toString();
            System.out.println(luckyNumber);
            while (lotteryService.isExistLuckyNumber(luckyNumber)){
                luckyNumber = "888" + Math.random()*1000;
            }
            Staff staff = new Staff()
                    .setStaffName(staffName)
                    .setPhone(phone)
                    .setLuckyNumber(luckyNumber);
            staff.save();
            renderJson("lucky_number",luckyNumber);
        }
    }

    /**
     * 根据名字和手机获取抽奖号码
     */
    public void showLuckyNumber(){
        String staffName = getPara("staff_name");
        String phone = getPara("phone");
        String luckyNumber = lotteryService.getLuckyNumber(staffName,phone).getLuckyNumber();
        renderJson("lucky_number",luckyNumber);
    }

    /**
     * 抽奖
     */
    public void bonus(){
        int quantity = getParaToInt("quantity");
        List<String> bonusNumberList = new ArrayList<>();
        List<String> luckyNumberList = lotteryService.getLuckyNumberList();
        int count = luckyNumberList.size();
        System.out.println(count);
        for (int i = 0;i < quantity;i++){
            Random random = new Random();
            //获取随机下标数
            int s = random.nextInt(count);
            //将抽到的随机数放到中奖数列中
            bonusNumberList.add(luckyNumberList.get(s));
            //将中奖数字置于"已中奖"
            lotteryService.update(luckyNumberList.get(s));
            //将中将数字从奖池中移除
            luckyNumberList.remove(s);
        }
        renderJson("bonus_number_list",bonusNumberList);
    }
}
